<template>
    <div class="app-container">
        <el-card class="box-card form-container">
            <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm" label-width="150px" class="demo-ruleForm"
                status-icon>
                <el-form-item label="分类名称：" prop="name">
                    <el-input v-model="ruleForm.name" />
                </el-form-item>
                <el-form-item label="上级分类：" prop="firstLetter">
                    <el-select v-model="ruleForm.parentId" placeholder="please select your zone">
                        <el-option label="无上级菜单" :value="0" />
                        <el-option v-for="item in pullDown" :label="item.name" :value="item.id!" />
                    </el-select>
                </el-form-item>
                <el-form-item label="数量单位：" prop="logo">
                    <el-input v-model="ruleForm.productUnit" />
                </el-form-item>
                <el-form-item label="排序：" prop="bigPic">
                    <el-input v-model="ruleForm.sort" />
                </el-form-item>
                <el-form-item label="是否显示：">
                    <el-radio-group v-model="ruleForm.showStatus">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否显示在导航栏：">
                    <el-radio-group v-model="ruleForm.navStatus">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="分类图标：">
                    <el-upload ref="upload" v-model:file-list="fileList" :auto-upload="false" :limit="1"
                        :on-exceed="handleExceed" :on-change="handleChange" list-type="picture">
                        <el-button type="primary">点击上传</el-button>
                        <template #tip>
                            <div class="el-upload__tip">只能上传jpg/png文件，且不超过100kb</div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="属性筛选：">
                    <el-cascader @change="find" ref="category" :options="pullDownOther" clearable
                        v-model="productAttributeIdLists" />
                    <el-button>
                        删除
                    </el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary">
                        新增
                    </el-button>
                </el-form-item>
                <el-form-item label="关键词：">
                    <el-input v-model="ruleForm.keywords" />
                </el-form-item>
                <el-form-item label="描述：">
                    <el-input v-model="ruleForm.description" type="textarea" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm()">
                        提交
                    </el-button>
                    <el-button @click="resetForm()">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import * as http from "@/request/http"
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref, watch } from 'vue';
import type { UploadProps, UploadUserFile, UploadRawFile, UploadInstance, FormRules, FormInstance, } from "element-plus";
import { useRouter, useRoute } from 'vue-router';

const router = useRouter()
const route = useRoute()

let ruleForm = ref<IproductCategoryCreate>({
    name: "",
    parentId: 0,
    productUnit: "",
    sort: 0,
    keywords: "",
    description: "",
    showStatus: 0,
    navStatus: 0,
    icon: "",
    productAttributeIdList: [],
})

const ruleFormRef = ref<FormInstance>()

const productAttributeIdLists = ref([])

const fileList = ref<UploadUserFile[]>([])

interface labAndVal {
    label: string;
    value: number;
    children: labAndValChi[]
}

interface labAndValChi {
    label: string;
    value: number;
}

const pullDown = ref<CateList[]>([])
const pullDownOther = ref<labAndVal[]>([])

const upload = ref<UploadInstance>(); // 获取el-upload的DOM

const handleExceed: UploadProps["onExceed"] = (files) => {
    upload.value!.clearFiles(); // clearFiles 清空已上传的文件列表（该方法不支持在 before-upload 中调用）
    const file = files[0] as UploadRawFile; // 拿到最新上传的文件
    upload.value!.handleStart(file); // handleStart 手动选择文件
};

const handleChange: UploadProps['onPreview'] = async (
    uploadFile
) => {
    const backupFileList = [...fileList.value]; // 备份已上传的文件，在新上传文件不符合要求的情况下，可以将以上传的文件重新赋值给文件列表
    const { type, size } = uploadFile.raw as UploadRawFile;
    const validTypes = ["image/jpeg", "image/jpg", "image/png"];
    const maxSize = 100 * 1024; // 单位byte
    if (!validTypes.includes(type) || size > maxSize) {
        ElMessage.error("只能上传jpg/png文件，且不超过100kb!");
        fileList.value = backupFileList; // 在新上传文件不符合要求的情况下，可以将以上传的文件重新赋值给文件列表
        return;
    }
    // 将文件通过接口给后端换取文件链接地址
    const formData = new FormData();
    formData.append("file", uploadFile.raw as UploadRawFile);
    http.minio.minioUpload(formData).then(res => {
        ruleForm.value.icon = res.data.url
    })
};

const find = (val: any) => {
    ruleForm.value.productAttributeIdList!.push(val[0])
}

const getPullDownMenu = () => {
    http.productCate.productCategoryList({
        pageNum: 1,
        pageSize: 10,
        parentId: 0
    }).then(res => {
        pullDown.value = res.data.list
    })
    http.productCate.productAttributeCategoryListWithAttr().then(res => {
        pullDownOther.value = res.data.map(item => {
            return {
                label: item.name,
                value: item.id,
                children: [
                    ...item.productAttributeList.map(el => {
                        return {
                            value: el.id,
                            label: el.name,
                        }
                    })
                ]
            }
        })
    })
}

getPullDownMenu()

const rules = reactive<FormRules>({
    name: [
        { required: true, message: '必填项', trigger: 'blur' },
    ],
})

const ruleForms = () => ({
    name: "",
    parentId: 0,
    productUnit: "",
    sort: 0,
    keywords: "",
    description: "",
    showStatus: 0,
    navStatus: 0,
    icon: "",
    productAttributeIdList: [],
})

const resetForm = () => {
    ruleFormRef.value?.resetFields()
    Object.assign(ruleForm, ruleForms())
}

const idNumber = route.query.id as unknown as number

const submitForm = async () => {
    ruleFormRef.value?.validate((valid) => {
        if (valid) {
            if (idNumber) {
                ElMessageBox.confirm(
                    '是否修改数据',
                    '警告',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                )
                    .then(() => {
                        http.productCate.productCategoryUpdate(ruleForm.value).then(() => {
                            ElMessage.success("修改成功")
                            router.push("productCate")
                        })
                    })
                    .catch(() => {
                        ElMessage({
                            type: 'info',
                            message: 'Delete canceled',
                        })
                    })
            } else {
                ElMessageBox.confirm(
                    '是否提交数据',
                    '警告',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                )
                    .then(() => {
                        http.productCate.productCategoryCreate(ruleForm.value).then(() => {
                            ElMessage({
                                type: 'success',
                                message: '提交成功',
                            })
                            Object.assign(ruleForm, ruleForms())
                        })
                    })
                    .catch(() => {
                        ElMessage({
                            type: 'info',
                            message: 'Delete canceled',
                        })
                    })
            }
        } else {
            ElMessage.warning("提交失败")
            return false
        }
    })
}

watch(
    () => route.query.id,
    () => {
        http.productCate.productCategoryId(idNumber).then(res => {
            ruleForm.value = res.data
            console.log(res.data);
            if (res.data.icon === "") return
            const parts = res.data.icon?.split("/");
            const result = parts![parts!.length - 1];
            fileList.value.push({ name: result, url: res.data.icon })
        })
    }, {
    immediate: true
}
)

</script>

<style lang="less" scoped>
.form-container {
    width: 720px;
    padding: 35px 35px 15px 35px;
    margin: 0 auto;
    margin-bottom: 35px;

    .form-content {
        margin-top: 50px;
    }
}
</style>